﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using System.Net.Sockets;
using System;

public class SocketObject 
{
    static Socket clientSocket;

    private static int serverPort = 10001;
    private static string serverIP   = "127.0.0.1";

    private static byte[] sendBuff = new byte[1024];
    private static byte[] recvBuff = new byte[1024];

    private static bool connected = false;
    private static List<string> msgList = new List<string>();

    public static bool Connected
    {
        get { return connected; }
    }
    public static List<string> MsgList
    {
        get { return msgList; }
    }


    public static void ConnectToServer()
    {
        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        clientSocket.Connect(serverIP, serverPort);
        connected = true;

        clientSocket.BeginReceive(recvBuff, 0, 100, 0, recvCb, clientSocket);
    }

    public static void SendString(string msg)
    {
        if (connected)
        {
            //Debug.Log("sendStr : " + msg);
            sendBuff = System.Text.Encoding.Default.GetBytes(msg);
            clientSocket.Send(sendBuff);
        }
    }

    public static void recvCb(IAsyncResult ar)
    {
        int num = clientSocket.EndReceive(ar);
        string recvStr = System.Text.Encoding.UTF8.GetString(recvBuff, 0, num);
        //Debug.Log(recvStr);
        msgList.Add(recvStr);
        clientSocket.BeginReceive(recvBuff, 0, 1024, 0, recvCb, clientSocket);
    }

    public static void Disconnect()
    {
        clientSocket.Shutdown(SocketShutdown.Both);
    }

}
